<script setup lang="ts">
import type { FormInst, FormRules } from 'naive-ui'
import { addCollector, updateCollector } from '@/service'

interface Props {
  visible: boolean
  type: 'add' | 'edit'
  modalData?: Api.Collector.Info | null
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  type: 'add',
  modalData: null,
})

const emit = defineEmits<Emits>()

const showModal = computed({
  get() {
    return props.visible
  },
  set(val) {
    emit('update:visible', val)
  },
})

const title = computed(() => {
  return props.type === 'add' ? '新建采集器' : '编辑采集器'
})

const loading = ref(false)
const formRef = ref<FormInst | null>(null)

// 采集器类型选项
const collectorTypes = [
  { label: '串口(Serial)', value: 'Serial' },
  { label: 'TCP客户端(TcpClient)', value: 'TcpClient' },
  { label: 'TCP服务端(TcpServer)', value: 'TcpServer' },
  { label: 'MQTT', value: 'Mqtt' },
]

const formData = ref<Api.Collector.AddRequest>({
  name: '',
  type: 'Serial',
  serial: {
    name: '',
    deviceName: '',
    baudRate: 9600,
    dataBit: 8,
    stopBit: '1',
    check: 'N',
  },
  tcpClient: {
    name: '',
    ip: '',
    port: 502,
  },
  tcpServer: {
    name: '',
    port: 502,
  },
  mqtt: {
    name: '',
  },
  timeout: 3000,
  interval: 200,
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入采集器名称', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择采集器类型', trigger: 'change' },
  ],
}

// 监听visible和modalData变化，初始化表单数据
watch(
  [() => props.visible, () => props.modalData, () => props.type],
  ([visible, data, type]) => {
    if (visible && data && type === 'edit') {
      formData.value = {
        name: data.name,
        type: data.type,
        serial: data.serial || {
          name: '',
          deviceName: '',
          baudRate: 9600,
          dataBit: 8,
          stopBit: '1',
          check: 'N',
        },
        tcpClient: data.tcpClient || {
          name: '',
          ip: '',
          port: 502,
        },
        tcpServer: data.tcpServer || {
          name: '',
          port: 502,
        },
        mqtt: data.mqtt || {
          name: '',
        },
        timeout: data.timeout || 3000,
        interval: data.interval || 200,
      }
    }
    else if (visible && type === 'add') {
      resetForm()
    }
  },
  { immediate: true },
)

function resetForm() {
  formData.value = {
    name: '',
    type: 'Serial',
    serial: {
      name: '',
      deviceName: '',
      baudRate: 9600,
      dataBit: 8,
      stopBit: '1',
      check: 'N',
    },
    tcpClient: {
      name: '',
      ip: '',
      port: 502,
    },
    tcpServer: {
      name: '',
      port: 502,
    },
    mqtt: {
      name: '',
    },
    timeout: 3000,
    interval: 200,
  }
}

function handleClose() {
  showModal.value = false
  resetForm()
}

async function handleConfirm() {
  try {
    await formRef.value?.validate()
    loading.value = true

    const apiCall = props.type === 'add' ? addCollector : updateCollector
    const { isSuccess, message } = await apiCall(formData.value)

    if (isSuccess) {
      window.$message.success(props.type === 'add' ? '添加成功' : '更新成功')
      emit('success')
      handleClose()
    }
    else {
      window.$message.error(message || '操作失败')
    }
  }
  catch (e: any) {
    if (e?.message) {
      window.$message.error(e.message)
    }
  }
  finally {
    loading.value = false
  }
}
</script>

<template>
  <n-modal
    v-model:show="showModal"
    :title="title"
    preset="card"
    :style="{ width: '700px' }"
    :segmented="{ content: true }"
  >
    <n-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-placement="left"
      label-width="120"
    >
      <n-form-item label="采集器名称" path="name">
        <n-input
          v-model:value="formData.name"
          placeholder="请输入采集器名称"
          :disabled="type === 'edit'"
        />
      </n-form-item>

      <n-form-item label="采集器类型" path="type">
        <n-select
          v-model:value="formData.type"
          :options="collectorTypes"
          placeholder="请选择采集器类型"
        />
      </n-form-item>

      <!-- Serial配置 -->
      <template v-if="formData.type === 'Serial'">
        <n-divider title-placement="left">
          串口配置
        </n-divider>
        <n-form-item label="串口名称" path="serial.name">
          <n-input v-model:value="formData.serial!.name" placeholder="如: COM1, /dev/ttyS0" />
        </n-form-item>
        <n-form-item label="设备名称" path="serial.deviceName">
          <n-input v-model:value="formData.serial!.deviceName" placeholder="请输入设备名称" />
        </n-form-item>
        <n-form-item label="波特率" path="serial.baudRate">
          <n-input-number v-model:value="formData.serial!.baudRate" :min="1" class="w-full" />
        </n-form-item>
        <n-form-item label="数据位" path="serial.dataBit">
          <n-input-number v-model:value="formData.serial!.dataBit" :min="5" :max="8" class="w-full" />
        </n-form-item>
        <n-form-item label="停止位" path="serial.stopBit">
          <n-select
            v-model:value="formData.serial!.stopBit"
            :options="[{ label: '1', value: '1' }, { label: '1.5', value: '1.5' }, { label: '2', value: '2' }]"
          />
        </n-form-item>
        <n-form-item label="校验位" path="serial.check">
          <n-select
            v-model:value="formData.serial!.check"
            :options="[
              { label: '无(N)', value: 'N' },
              { label: '偶校验(E)', value: 'E' },
              { label: '奇校验(O)', value: 'O' },
            ]"
          />
        </n-form-item>
      </template>

      <!-- TcpClient配置 -->
      <template v-if="formData.type === 'TcpClient'">
        <n-divider title-placement="left">
          TCP客户端配置
        </n-divider>
        <n-form-item label="名称" path="tcpClient.name">
          <n-input v-model:value="formData.tcpClient!.name" placeholder="请输入名称" />
        </n-form-item>
        <n-form-item label="IP地址" path="tcpClient.ip">
          <n-input v-model:value="formData.tcpClient!.ip" placeholder="如: 192.168.1.100" />
        </n-form-item>
        <n-form-item label="端口" path="tcpClient.port">
          <n-input-number v-model:value="formData.tcpClient!.port" :min="1" :max="65535" class="w-full" />
        </n-form-item>
      </template>

      <!-- TcpServer配置 -->
      <template v-if="formData.type === 'TcpServer'">
        <n-divider title-placement="left">
          TCP服务端配置
        </n-divider>
        <n-form-item label="名称" path="tcpServer.name">
          <n-input v-model:value="formData.tcpServer!.name" placeholder="请输入名称" />
        </n-form-item>
        <n-form-item label="监听端口" path="tcpServer.port">
          <n-input-number v-model:value="formData.tcpServer!.port" :min="1" :max="65535" class="w-full" />
        </n-form-item>
      </template>

      <!-- Mqtt配置 -->
      <template v-if="formData.type === 'Mqtt'">
        <n-divider title-placement="left">
          MQTT配置
        </n-divider>
        <n-form-item label="名称" path="mqtt.name">
          <n-input v-model:value="formData.mqtt!.name" placeholder="请输入名称" />
        </n-form-item>
      </template>

      <!-- 通用配置 -->
      <n-divider title-placement="left">
        通用配置
      </n-divider>
      <n-form-item label="超时时间(ms)" path="timeout">
        <n-input-number
          v-model:value="formData.timeout"
          placeholder="请输入超时时间"
          :min="0"
          class="w-full"
        />
      </n-form-item>

      <n-form-item label="采集间隔(ms)" path="interval">
        <n-input-number
          v-model:value="formData.interval"
          placeholder="请输入采集间隔"
          :min="0"
          class="w-full"
        />
      </n-form-item>
    </n-form>

    <template #footer>
      <n-space justify="end">
        <n-button @click="handleClose">
          取消
        </n-button>
        <n-button type="primary" :loading="loading" @click="handleConfirm">
          确定
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

